import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 功能：批量替换 Android 工程中的中文字符串 (.xml 文件)
public class ChineseReplacer {
    // 存储唯一内容和对应的键
    private static final LinkedHashMap<String, String> keyValueMap = new LinkedHashMap<>();
    private static final Map<String, String> contentToKeyMap = new HashMap<>();
    private static int keyCounter = 1;

    public static void main(String[] args) {
        Path rootPath = Paths.get(AddInfo.filePath);

        try {
            // 第一遍：收集所有唯一中文内容
            collectChineseStrings(rootPath);

            // 第二遍：执行实际替换
            replaceChineseStrings(rootPath);

            // 输出生成的键值对
            System.out.println("\n生成的键值对：");
            keyValueMap.forEach((k, v) -> System.out.println("<string name=\""+k+"\">"+v+"</string>)"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void collectChineseStrings(Path root) throws IOException {
        Files.walk(root)
                .filter(Files::isRegularFile)
                .filter(p -> p.toString().endsWith(".xml"))
                .filter(p -> !p.getFileName().toString().equalsIgnoreCase("strings.xml"))
                .filter(p -> !p.getFileName().toString().equalsIgnoreCase("themes.xml"))
                .forEach(path -> {
                    try {
                        String content = Files.readString(path, StandardCharsets.UTF_8);
                        Pattern pattern = Pattern.compile("\"((?:\\\\\"|[^\"\\r\\n])*?[\u4E00-\u9FA5]+(?:\\\\\"|[^\"\\r\\n])*?)\"");
                        Matcher matcher = pattern.matcher(content);

                        while (matcher.find()) {
                            String rawContent = matcher.group(1)
                                    .replace("\\\"", "\"");  // 处理转义引号

                            if (!contentToKeyMap.containsKey(rawContent)) {
                                String key = "string" + keyCounter++;
                                keyValueMap.put(key, rawContent);
                                contentToKeyMap.put(rawContent, key);
                            }
                        }
                    } catch (IOException e) {
                        System.err.println("读取文件失败: " + path);
                    }
                });
    }

    private static void replaceChineseStrings(Path root) throws IOException {
        Files.walk(root)
                .filter(Files::isRegularFile)
                .filter(p -> p.toString().endsWith(".xml"))
                .filter(p -> !p.getFileName().toString().equalsIgnoreCase("strings.xml"))
                .forEach(path -> {
                    try {
                        String content = Files.readString(path, StandardCharsets.UTF_8);
                        Pattern pattern = Pattern.compile("\"((?:\\\\\"|[^\"\\r\\n])*?[\u4E00-\u9FA5]+(?:\\\\\"|[^\"\\r\\n])*?)\"");
                        Matcher matcher = pattern.matcher(content);

                        StringBuffer sb = new StringBuffer();
                        while (matcher.find()) {
                            String rawContent = matcher.group(1)
                                    .replace("\\\"", "\"");  // 统一处理转义字符

                            String key = contentToKeyMap.get(rawContent);
                            matcher.appendReplacement(sb, "\"@string/" + key + "\"");
                        }
                        matcher.appendTail(sb);

                        // 写入修改后的内容
                        Files.write(path, sb.toString().getBytes(StandardCharsets.UTF_8));
                        System.out.println("已更新文件: " + path);

                    } catch (IOException e) {
                        System.err.println("处理文件失败: " + path);
                    }
                });
    }
}